<?php
declare (strict_types=1);

namespace app\common\tool\encrypt;

class Rsa
{
    private $publicKey;

    private $privateKey;

    public function __construct()
    {
        $path = app()->getBasePath() . '/common/tool/encrypt/pem/';
        //读取公私钥
        $this->publicKey = file_get_contents($path . 'rsa_public_key.pem');
        $this->privateKey = file_get_contents($path . 'rsa_private_key.pem');
    }

    /**
     * 验证签名，加密方式为公钥加密，私钥解密
     * @param string $data
     * @return array|mixed
     * @throws RsaException
     */
    public function verifySign(string $data)
    {
        return $this->decrypt($data);
    }

    /**
     * @param string $data - 要加密的数据
     * @return string
     * @throws RsaException
     * 原点 2022年10月19日13:52:50 加密字符串
     */
    public function encrypt(array $data)
    {
        $key = openssl_pkey_get_public($this->publicKey);
        if (!$key) {
            throw new RsaException('解析publicKey失败，请检查');
        }
        $return_en = openssl_public_encrypt(json_encode($data), $encrypt, $key);
        if (!$return_en) {
            throw new RsaException('加密失败');

        }
        return base64_encode($encrypt);
    }

    /**
     * @param string $data - 要解密的数据
     * @return mixed
     * @throws RsaException
     * 原点 2022年10月19日13:53:03 解密字符串
     */
    public function decrypt(string $data, $deJson = false)
    {
        $private_key = openssl_pkey_get_private($this->privateKey);
        if (!$private_key) {
            throw new RsaException('解析失败，请检查privateKey');
        }
        $result = openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
        if (!$result) {
            throw new RsaException('解密失败');
        }
        return ['code' => 1, 'message' => 'success', 'data' => $deJson ? json_decode($decrypted, true) : $decrypted];

    }

}